function m = opt_dist(v1, v2, c)
% c(1) offset from -0.5 to 0.5, c(2) stretch x, c(3) stretch y
n=400;
Ln = linspace(0,1,n);
%Lnshift = linspace(0.5 + c(1) - c(2) * 0.5,...
    %0.5 + c(1) + c(2) * 0.5, n);
Lnshift = linspace(c(1),c(1)+c(2),n);
    
    
v1 = interp1(linspace(0, 1, length(v1)), v1, Ln);
v2 = interp1(linspace(0, 1, length(v2)), v2, Ln);
%plot(linspace(0,1,length(v1)),[v1; v2]); hold on;
%v2 = c(3)*v2; 
v2 = v2/c(2); %Trying to scale curvature inversely with stretch
%plot(linspace(0,1,length(v1)),[v2]);
v2 = interp1(Lnshift, v2, Ln);
%plot(linspace(0,1,length(v1)),[v2]);

         % Change to get actual distance transform
%m = sqrt(nansum((v1 - v2).^2))/n;
%This totally isn't right - should be comparing the smallest distance
%values to each other
V = bsxfun(@minus,v1,v2');
srange = [max(min([Ln; Lnshift],[],2)) min(max([Ln; Lnshift],[],2))];
Ln(Ln < srange(1) | Ln > srange(2)) = nan;
Lnshift(Lnshift < srange(1) | Lnshift > srange(2)) = nan;
s = bsxfun(@minus,Ln,Lnshift');

d = min(sqrt(V.^2+s.^2),[],1); 
%d(isnan(d)) = [];  d = interp1(1:length(d), d,linspace(1,length(d),400));

ids1 = [find(~isnan(v2)&~isnan(Lnshift),1,'first'), find(~isnan(v2)&~isnan(Lnshift),1,'last')];
x1 = Lnshift(ids1(2))-Lnshift(ids1(1));
ids2 = [find(~isnan(v1)&~isnan(Ln),1,'first'), find(~isnan(v1)&~isnan(Ln),1,'last')];
x2 = Lnshift(ids2(2))-Lnshift(ids2(1));
xlen = min([x1, x2]);

%Fixed 200521
m = nansum(d)/sum(~isnan(d))/sqrt(xlen); 


%Trying a new metric, 191119
%figure(11); plot(Ln,v1); hold on; plot(Lnshift,v2); hold off; title(num2str(m));
%arclen = nansum(sqrt((diff(v2)).^2+(diff(Lnshift)).^2));
%m = nansum(d)/arclen;

end